package org.onionframework.persistence.dao.processor;


import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Subqueries;
import org.onionframework.persistence.dao.CriteriaBuilder;
import org.onionframework.persistence.dao.PropertyFilterProcessor;
import org.onionframework.persistence.dao.expression.OnionExpressions;
import org.onionframework.persistence.query.OnionQuery;

public class HasProcessor implements PropertyFilterProcessor {

	@Override
	public Criterion buildCriterion(String alias, String name, Object value,
			CriteriaBuilder context) {
		if (value instanceof OnionQuery) {
			OnionQuery propertyFilterList = (OnionQuery) value;
			
			Class<?> targetClass = (Class<?>) propertyFilterList
					.getAttribute(OnionQuery.ATTR_KEY_CLASS);

			if (targetClass == null)
				throw new RuntimeException(context.getEntityClass().getName() + "."
						+ name + "不是实体类集合");

			DetachedCriteria dc = new CriteriaBuilder(context.getSession()).buildDetachedCriteria(propertyFilterList);
			
			dc.setProjection(Projections.id());
			dc.add(OnionExpressions.has(alias, context.value()));

			return Subqueries.exists(dc);
		} else {
			throw new RuntimeException("HAS查询只允许OnionQuery值");
		}
	}

}
